const db = require("../../db/sql");
const knex = require("../../db/knex");
const resetTableId = require("../../utils/resetTableId");

async function saveOperation(params) {
    let {id, title, recommend, question_list, create_time} = params
    let questionnaireInfo = {
        id, title, recommend, create_time
    }
    console.log(question_list[1],"添加里的id",question_list[1].id)
    let questionInfoArr = question_list.map((item, index) => ({
        name: item.name,
        type: item.type,
        label: item.label,
        option_num: item.option_num,
        questionnaire_id: id,
        question_id: item.question_id==undefined?item.id :item.question_id
    }))
    console.log(questionInfoArr,'map后')
    let optionsInfoArr = []//选项数组
    question_list.forEach((o, i) => {

        o.optionList.forEach(item => {
            item.question_id = o.question_id==undefined?o.id:o.question_id
            // console.log(o.optionList,'选项列表,很只要')
            optionsInfoArr.push(item) //将问题的选项加入选项数组
        })
    })
    optionsInfoArr.forEach(o => {
        o.questionnaire_id = id
    })
    // console.log(questionInfoArr, '问题列表', optionsInfoArr, '选项列表')

    try {
        let saveQuestionOptionsResult
        let saveQuestionResult
        let saveQuestionnaireResult
        await knex.transaction(async (trx) => {
            // console.log(questionnaireInfo, questionInfoArr, optionsInfoArr)
            saveQuestionOptionsResult = await trx('option_list').insert(optionsInfoArr)
            saveQuestionResult = await trx('question_list').insert(questionInfoArr)
            saveQuestionnaireResult = await trx('save_questionnaire').insert(questionnaireInfo)
        })
    } catch (e) {

    }
}
    async function saveQuestionnaire(params, res) {

        try{
            await saveOperation(params)
            res.send({
                msg:"添加成功"
                // saveQuestionnaireResult,
                // saveQuestionResult,
                // saveQuestionOptionsResult
            })
        } catch (e) {
            console.log(e)
        } finally {
            // await knex.destroy()
        }


    }

    module.exports = {saveQuestionnaire,saveOperation}

